import http from '../lib/request/index';
import {url, string, obj, date, file, number} from '../lib/index';
import Cookie from '../lib/cookie/index';

//将科学计数法转换为小数
const toNonExponential = (num) => {
    let m = (num + '').match(/\d(?:\.(\d*))?e([+-]\d+)/);
    return num.toFixed(Math.max(0, (m[1] || '').length - m[2]));
};
/**
 *  统一处理金额数值
 * @param number
 * @returns {string}
 */
const formateNumber = (num) => {
    num = Math.floor(parseFloat(number.multiplication(num, 1000000000)));
    num = number.division(num, 1000000000);
    /**
     * 将科学计数法改为正常显示
     */
    if ((num + '').match(/\d(?:\.(\d*))?e([+-]\d+)/)) {
        num = toNonExponential(num);
    }

    return getThousandNum(num);
};

const getThousandNum = (num) => {
    return (num || 0).toString().replace(/\d+/, function (n) {
        var len = n.length;
        if (len % 3 === 0) {
            return n.replace(/(\d{3})/g, ',$1').slice(1);
        } else {
            return n.slice(0, len % 3) + n.slice(len % 3).replace(/(\d{3})/g, ',$1');
        }
    });
};
const plain = (data) => {
    return JSON.parse(JSON.stringify(data));
};

const getLocalTime = (d, i = 0) => {
    //参数i为时区值数字，比如北京为东八区则输进8,西5输入-5
    if (typeof i !== 'number') return;

    //得到1970年一月一日到现在的秒数

    let len = d.getTime();

    //本地时间与GMT时间的时间偏移差

    let offset = d.getTimezoneOffset() * 60000;
    //得到现在的格林尼治时间

    let utcTime = len + offset;

    return new Date(utcTime + 3600000 * i);
};
/**
 * 时区
 * @param {*} timestampOrDate
 * @param {*} fmt
 */
const formatDate = (timestampOrDate, fmt, i = 0) => {
    const _date = getLocalTime(timestampOrDate, 0);
    return date.formatDate(_date, fmt);
};
const higherComponent = {
    cookieUtil: Cookie,
    plainObject: plain,
    objUtil: obj,
    numberUtil: number,
    fileUtil: file,
    stringUtil: string,
    ajax: http.ajax,
    urlUtil: url,
};
export default higherComponent;
